<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        #outer {
            border: 1px solid green;
            width: 700px;
            height: 800px;
            margin: auto;
            padding-top: 20px;
        }

        table {
            margin: auto;
        }

        table,
        th,
        td {
            border: 1px solid #ccc;
            border-collapse: collapse;
        }

        th,
        td {
            width: 120px;
            height: 30px;
            text-align: center;
        }
        #add_btn{
            color: #fff;
            background-color: green;
            border: 0;
            width: 100px;
            height: 30px;
            border-radius: 5px;
        }

        #del_btn{
            color: #fff;
            background-color: red;
            border: 0;
            width: 100px;
            height: 30px;
            border-radius: 5px;
        }

        #outer a{
            text-decoration: none;
            color: red;
            font-size: 12px;
        }
        #phone_name{
            height: 25px;
            width: 200px;
            border: 1px solid orangered;
            border-radius: 5px;
        }

        #search_btn{
            color: #fff;
            background-color: green;
            border: 0;
            width: 100px;
            height: 30px;
            border-radius: 5px;
        }
    </style>
</head>

<body>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.js"></script>
    <script src="data.json"></script>
    <div id="outer">

        <div style='width: 616px;margin: auto'>
            <h5>任务一:全选和全不选;任务二:完成添加一行</h5>
            <h6>任务三:删除选中行;任务四:删除单行</h6>
            <h6>任务五:模糊查询</h6>
            <h6>任务六:改变购物车数量 => 可编辑表格<br>
               1. 双击td-td内部会出现一个input输入框<br>
               2. td内部原来的值应该要被设置到这个input框中<br>
               3. 可以在input框中重新输入一个数量
               4. 给这个input增加onblur事件=>td中移除input,input输入的新值要出现在td中
            </h6>
        </div>

        <div style="width: 616px;margin: auto;">
            <button id="add_btn" type="button" onclick="addLine()">添加一行</button>
            <button id="del_btn" type="button" onclick="delmore()">删除选中行</button>
        </div>
        <div style="width: 616px;margin:5px auto;">
            <!-- 失去焦点事件onblur -->
            <input type="text" id="phone_name" placeholder="输入商品名称模糊查询">
            <button id="search_btn" type="button" onclick="search()">查询</button>
        </div>
        <div style="margin-top: 5px;">
            <table>
                <thead>
                    <tr>
                        <th><input type="checkbox" id="ckall"></th>
                        <th>序号</th>
                        <th>商品名称</th>
                        <th>单价</th>
                        <th>购买数量</th>
                        <th>操作选项</th>
                    </tr>
                </thead>
                <tbody id="tbl_phone">
                    <!-- <tr>
                        <td><input type="checkbox" class="ck"></td>
                        <td>1001</td>
                        <td>iphone16</td>
                        <td>4999.99</td>
                        <td ondblclick="change_num(this)">3</td>
                        <td><a href="#" class="del">删除</a></td>
                    </tr> -->

                </tbody>
                <tfoot>
                    <tr>
                        <td colspan="5">
                            <span style="color: red;font-size: 20px;">总价:<span id="total_span">0元</span></span>
                        </td>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>
    <script src="../js/decimal.js"></script>
    <script>
        $(function() {
            $.get('data/cart.json', function(res) {
                if (res.code == 200) {
                    let tbody = $("#tbl_phone");
                    let arr = res.products;
                    let str = "";

                    // 遍历 JSON 数据
                    for (let i = 0; i < arr.length; i++) {
                        str += `
                            <tr>
                                <td><input type="checkbox" class="ck"></td>
                                <td>${arr[i].id}</td>
                                <td>${arr[i].name}</td>
                                <td>${arr[i].price}</td>
                                <td ondblclick="change_num(this)">${arr[i].quantity}</td>
                                <td><a href="#" class="del">删除</a></td>
                            </tr>
                        `;
                    }
                    tbody.html(str);
                }
            })
        });


        //获取所有的ck
        //真正返回的是NodeList对象
        let cks = document.querySelectorAll(".ck");
        let total_span = document.querySelector("#total_span");
        let delone = document.querySelectorAll(".del");

        function cli () {
            // cks = document.querySelectorAll(".ck");
            // console.log(cks)
            //定义一个总价
            let total = 0.0;
            //选择被勾选的
            // for(let i=0;i<cks.length;i++){
            //     if(cks[i].checked){
            //         console.log(cks[i])
            //     }
            // }

            //filter方法=>只能是数组对象去调用
            //将NodeList对象转换成数组对象Array.from(obj)
            //不会对原来的数组造成影响
            // filter 是数组的方法，它的作用是筛选符合条件的元素,并返回一个新数组。
            //c => c.checked 是箭头函数，等价于：
                    // function (c) {
                    //     return c.checked;
                    // }
            //.filter(c => c.checked) 筛选出所有 checked == true 的复选框，返回只包含选中项的新数组。
            let all_checked = Array.from(cks).filter(c => c.checked)
            //继续遍历所有选中的
            all_checked.forEach(cc => {
                //获取数量
                let num_ele = cc.parentElement.parentElement.lastElementChild.previousElementSibling
                //获取单价
                let price_ele = num_ele.previousElementSibling

                let n = new Decimal(num_ele.innerText)
                let p = new Decimal(price_ele.innerText)
                total += parseFloat(n.times(p))
                //计算总价
                //total+=parseFloat(num_ele.innerText.trim()*price_ele.innerText.trim())
            })
            total_span.innerHTML = total + "元";
        }

        //遍历这个nodeList,支持forEach
        cks.forEach(ck => {
            // cks = document.querySelectorAll(".ck");
            ck.onclick = cli;
        })

        // 全选和全不选
        let ck_all = document.getElementById("ckall");
        ck_all.onclick = function(){
            cks = document.querySelectorAll(".ck")
            if(ck_all.checked){
                let total = 0.0;
                cks.forEach(c2 => {
                    c2.checked = true;  // 全选
                    // 计算价格
                    //获取数量
                    let num_ele = c2.parentElement.parentElement.lastElementChild.previousElementSibling
                    //获取单价
                    let price_ele = num_ele.previousElementSibling

                    let n = new Decimal(num_ele.innerText)
                    let p = new Decimal(price_ele.innerText)
                    total += parseFloat(n.times(p))
                })
                total_span.innerHTML = total + "元";
            }else{
                cks.forEach(c2 => {
                    c2.checked = false;
                })
                total_span.innerHTML = 0 + "元";
            }
        }

        //添加一行
        function addLine(){
            cks = document.querySelectorAll(".ck")
            let tbody=document.querySelector("tbody")

            let add=document.createElement("tr")
            tbody.appendChild(add)

            let td = document.createElement("td")
            add.appendChild(td)

            let inp=document.createElement("input")
            inp.type="checkbox"
            inp.className="ck"
            td.appendChild(inp)

            cks = document.querySelectorAll(".ck");  // 更新cks
            // console.log(cks)
            inp.onclick=cli;  // 绑定单击事件

            let td1=document.createElement("td")
            td1.innerText=1001+cks.length
            add.appendChild(td1)

            let td2=document.createElement("td")
            td2.innerText="iphone1"+Math.round(Math.random()*10)
            add.appendChild(td2)

            let td3=document.createElement("td")
            td3.innerText=Math.round((Math.random()*1000+1000)*100)/100  // 两位小数
            add.appendChild(td3)

            let td4=document.createElement("td")
            td4.innerText=Math.round(Math.random()*10+1)
            add.appendChild(td4)

            let td5=document.createElement("td")
            add.appendChild(td5)
            let a=document.createElement("a")
            a.href="#"
            a.className="del"
            a.textContent="删除"
            td5.appendChild(a)
            a.onclick = function(){
                removelin(a)
            };
            // delone = document.querySelectorAll(".del");  // 更新delone
        }

        //删除选中行
        function delmore(){
            cks.forEach(ck => {
                if(ck.checked){
                    removelin(ck);
                }
                total_span.innerHTML = 0 + "元";
            })
        }

        //删除单行
        delone.forEach(btn => {
            btn.onclick = function(){
                removelin(btn)
            };
        });

        //删除行的封装
        function removelin(btn){
            let row = btn.parentElement.parentElement;
            row.remove();
        }

        //模糊查询
        function search(){
            let text = document.getElementById("phone_name").value;
            // console.log(name);
            cks.forEach(ck=>{
                
                ck.parentElement.parentElement.style="display:none"
                let name=ck.parentElement.nextElementSibling.nextElementSibling.innerText

                if(name.includes(text)){
                    ck.parentElement.parentElement.style="display:"
                }
            })
        }

        //任务六:改变购物车数量 => 可编辑表格<br>
        // 1. 双击td-td内部会出现一个input输入框<br>
        //        2. td内部原来的值应该要被设置到这个input框中<br>
        //        3. 可以在input框中重新输入一个数量
        //        4. 给这个input增加onblur事件=>td中移除input,input输入的新值要出现在td中
        function change_num(td) {
            let oldValue = td.innerText;

            let input = document.createElement("input");
            input.type = "number";
            input.value = oldValue;  // 赋值给输入框
            input.style.width = "50px";
            // 清空 td 的内容并插入 input
            td.innerText = "";
            td.appendChild(input);
            // 让 input 自动获得焦点
            input.focus();
            // 监听失去焦点事件
            input.onblur = function () {
                let newValue = input.value.trim();  // 获取用户输入的新值

                if (newValue === "" || isNaN(newValue) || newValue < 1) {
                    newValue = oldValue; // 如果输入无效，恢复原值
                }

                td.innerText = newValue; // 更新 td 内容
            };
            // 监听回车键直接提交新值
            input.onkeypress = function (event) {
                if (event.key === "Enter") {
                    input.blur();  // 触发 onblur 事件
                }
            };
        }
    </script>
</body>

</html>